package com.hyj.demo

import io.vertx.core.AbstractVerticle
import io.vertx.core.Future
import io.vertx.core.Vertx
import io.vertx.core.http.HttpServerResponse
import io.vertx.core.logging.Logger
import io.vertx.core.logging.LoggerFactory

class MainVerticle : AbstractVerticle() {

  val logger: Logger = LoggerFactory.getLogger(this.javaClass)

  companion object {
    @JvmStatic
    fun main(args: Array<String>) {
      System.setProperty("vertx.logger-delegate-factory-class-name", "io.vertx.core.logging.Log4j2LogDelegateFactory")
      Vertx.vertx().deployVerticle(MainVerticle())
    }
  }

  override fun start(startFuture: Future<Void>) {
    vertx
      .createHttpServer()
      .requestHandler { req ->
        req.response()
          .plain()
          .end("Hello from Vert.x hyj!")
      }
      .listen(8080) { http ->
        if (http.succeeded()) {
          startFuture.complete()
          println("HTTP server started on port 8080")
        } else {
          startFuture.fail(http.cause())
        }
      }

  }

  fun HttpServerResponse.plain(): HttpServerResponse {
    return this.putHeader("content-type", "text/plain")
  }

  fun HttpServerResponse.html(): HttpServerResponse {
    return this.putHeader("content-type", "text/html")
  }

  fun HttpServerResponse.json(): HttpServerResponse {
    return this.putHeader("content-type", "application/json; charset=utf-8")
  }

}
